import express from 'express';
import sql from '../../sql.js';
const router = express.Router();

// 获取私信接口
router.post('/searchMessage', async (req, res) => {
  const userId = req.body.userId;
  const isRead = req.body.isRead;
  let page = parseInt(req.body.page) || 1;
  const pageSize = parseInt(req.body.pageSize) || 10;
  let messages;

  // 构建查询基础部分
  let query = 'SELECT m.* ';
  query += 'FROM message m ';
  let whereClauses = [];
  let values = [];

  // 根据参数添加条件
  if (userId) {
      whereClauses.push('m.user_id =?');
      values.push(userId);
  }
  if (isRead !== undefined) {
      whereClauses.push('m.is_read = ?');
      values.push(isRead);
  }

  if (whereClauses.length > 0) {
      query += ' WHERE ' + whereClauses.join(' AND ');
  }

  // 分页
  query += ' LIMIT ?,?';
  values.push((page - 1) * pageSize, pageSize);

  // 计算总数
  const countQuery = `SELECT COUNT(*) AS totalCount FROM message as m ${whereClauses.length > 0? ' WHERE ' + whereClauses.join(' AND ') : ''}`;
  const [countResult] = await sql.query(countQuery, values);
  const totalCount = countResult[0].totalCount;
  const totalPages = Math.ceil(totalCount / pageSize);
  const noReadQuery = 'SELECT COUNT(*) AS noReadCount FROM message WHERE is_read = 0';
  const [noReadResult] = await sql.query(noReadQuery);
  const noRead = noReadResult[0].noReadCount;

  try {
      [messages] = await sql.query(query, values);

      if (messages.length === 0 && page > 1) {
        page = page - 1;
        values[values.length-2] = (page - 1) * pageSize;
        const [data] = await sql.query(query, values);
        messages = data;
     }

      res.send({
          status: 'success',
          message: '私信查询成功',
          data: messages,
          pagination: {
              currentPage: page,
              pageSize: pageSize,
              totalCount: totalCount,
              totalPages: totalPages
          },
          noRead: noRead
      });
  } catch (error) {
      console.error('查询错误：', error);
      res.send({
          status: 'error',
          message: '服务器内部错误',
          errorCode: 500
      });
  }
});

// 更新私信状态接口
router.put('/updateMessageReadStatus/:messageId', async (req, res) => {
  const messageId = req.params.messageId;
  try {
      const query = 'UPDATE message SET is_read = 1 WHERE ID =?';
      await sql.query(query, [messageId]);
      res.send({
          status: 'success',
          message: '私信状态更新成功'
      });
  } catch (error) {
      console.error('更新私信状态错误：', error);
      res.send({
          status: 'error',
          message: '服务器内部错误',
          errorCode: 500
      });
  }
});

 // 删除评论接口
 router.delete('/deleteMessage/:messageId', async (req, res) => {
    const messageId = req.params.messageId;
    try {
        const query = 'DELETE FROM message WHERE ID =?';
        await sql.query(query, [messageId]);
        res.send({
            status: 'success',
            message: '私信删除成功'
        });
    } catch (error) {
        console.error('删除私信错误：', error);
        res.send({
            status: 'error',
            message: '服务器内部错误',
            errorCode: 500
        });
    }
  });


export default router;
